package com.baizhi.cmfz.aspect;

import com.baizhi.cmfz.annotation.LogAnnotation;
import com.baizhi.cmfz.dao.LogDao;
import com.baizhi.cmfz.entity.Admin;
import com.baizhi.cmfz.entity.Log;
import com.baizhi.cmfz.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * @Configuration 标注这个类是配置类
 * @Aspect 增强
 * */
@Configuration
@Aspect
public class LogAspect {
    private Logger logger= LoggerFactory.getLogger(LogAspect.class);
    @Autowired
    private LogDao logDao;

    @After("@annotation(com.baizhi.cmfz.annotation.LogAnnotation)")
    public  void logAspect(JoinPoint joinPoint){
            Log log=new Log();
            //获取日期
        log.setLogDate(new Date());
        //通过session获取admin的id
        ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request=requestAttributes.getRequest();
        HttpSession session=request.getSession();
        logger.debug(session.toString());
        Admin admin= (Admin) session.getAttribute("admin");
        log.setAid(admin.getId());
        //通过工具类获取ip
        log.setIp(IPKit.getIpAddrByRequest(request));
        //获取内容
        MethodSignature signature= (MethodSignature) joinPoint.getSignature();
        Method method=signature.getMethod();
        LogAnnotation logAnnotation=method.getAnnotation(LogAnnotation.class);
        String value=logAnnotation.value();
        log.setContent(value);
        //操作类型
        String type=logAnnotation.type();
        log.setType(type);
        logger.debug(log.toString());
        //添加数据库
        logDao.insertLog(log);
    }
}
